<template>
  <Dialog title="引用" v-model="dialogVis" width="1400px">
    <el-form ref="formRef" :model="formData" class="mt-12px">
      <el-form-item style="padding-bottom: 20px">
        <el-button type="primary" @click="handleImport"> 引用文件管理 </el-button>
        <el-button type="primary" @click="handleDelete">删除 </el-button>
      </el-form-item>
      <el-table :data="tableData" height="500" border ref="tableRef">
        <el-table-column type="selection" width="55" />
        <el-table-column label="源文件名称" min-width="150px" prop="fileName">
          <template #default="scope">
            <el-form-item
              :prop="`tableData[${scope.$index}].fileName`"
              :rules="[{ required: true, message: `文件名称不能为空` }]"
            >
              <ns-input v-model="tableData[scope.$index].fileName" disabled />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="源文件类型" min-width="100px" prop="fileName">
          <template #default="scope">
            <el-form-item :prop="`tableData[${scope.$index}].fileType`">
              <ns-input v-model="tableData[scope.$index].fileType" disabled
            /></el-form-item>
          </template>
        </el-table-column>
        <!-- <el-table-column label="文件来源" width="150px" prop="path">
          <template #default="scope">
            <el-form-item :prop="`tableData[${scope.$index}].path`">
              <el-select
                v-model="tableData[scope.$index].path"
                clearable
                placeholder="请选择文件来源"
              >
                <el-option label="手动上传" :value="3" />
                <el-option label="转储文件" :value="4" />
                <el-option label="监测平台" :value="5" /> </el-select
            ></el-form-item>
          </template>
        </el-table-column> -->
        <el-table-column label="文件大小" min-width="100px" prop="fileSize">
          <template #default="scope">
            <el-form-item :prop="`tableData[${scope.$index}][fileSize]`">
              <ns-input v-model="tableData[scope.$index].fileSize" disabled
            /></el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="数据标准" min-width="200px" prop="standard">
          <template #default="scope">
            <el-form-item
              :prop="`tableData[${scope.$index}][standard]`"
              :rules="[{ required: true, message: `数据标准不能为空` }]"
            >
              <el-select
                v-model="tableData[scope.$index].standard"
                filterable
                @change="templateChange(scope.$index)"
                placeholder="请选择数据标准"
              >
                <el-option
                  v-for="(template, templateIndex) in templateList"
                  :key="templateIndex"
                  :label="template.dataStandardName"
                  :value="template.id"
                /> </el-select
            ></el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="分类" min-width="150px" prop="classification">
          <template #default="scope">
            <el-form-item
              :prop="`tableData[${scope.$index}][classification]`"
              :rules="[{ required: true, message: `分类不能为空` }]"
            >
              <div style="width: 100%">
                <el-cascader
                  :filter-method="sysFilterMethod"
                  @change="classificationChange($event, scope.$index)"
                  placeholder="请选择分类"
                  v-model="tableData[scope.$index].classification"
                  :options="tableData[scope.$index].classOptions"
                  :props="classProps"
                  filterable
                />
              </div>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="等级" min-width="100px" prop="level">
          <template #default="scope">
            <el-form-item
              :prop="`tableData[${scope.$index}][level]`"
              :rules="[{ required: true, message: `等级不能为空` }]"
            >
              <el-select
                v-model="tableData[scope.$index][`level`]"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="item in cascaderAllOptions?.[scope.$index]?.[`field1`]"
                  :key="item[`field2`]"
                  :value="item[`field2`]"
                  :label="item[`field2_name`]"
                />
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="归属机构" min-width="200px" prop="deptId">
          <template #default="scope">
            <el-form-item :prop="`tableData[${scope.$index}].deptId`">
              <el-cascader
                ref="deptCascader"
                v-model="tableData[scope.$index].deptId"
                placeholder="请选择归属机构"
                :props="cascaderProps"
                :options="deptList"
                filterable
                clearable
                value-on-clear=""
                :filter-method="sysFilterMethod"
              />
            </el-form-item>
          </template>
        </el-table-column>

        <el-table-column label="归属系统" min-width="200px" prop="systemId">
          <template #default="scope">
            <el-form-item :prop="`tableData[${scope.$index}].systemId`">
              <el-cascader
                ref="systemCascader"
                v-model="tableData[scope.$index].systemId"
                placeholder="请选择归属系统"
                :props="systemCascaderProps"
                :options="systemList"
                filterable
                clearable
                value-on-clear=""
                :filter-method="sysFilterMethod"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          label="文件指纹"
          align="center"
          width="200px"
          :formatter="(row) => renderFinger({ row })"
        />
      </el-table>
    </el-form>
    <template #footer>
      <div class="footer-wrap">
        <div>
          <el-button @click="dialogVisible = false">关 闭</el-button>

          <el-button type="primary" @click="confirmImport">确 定</el-button>
        </div>
      </div>
    </template>
  </Dialog>
  <FileChose ref="fileChoseRef" @success="open" />
</template>
<script setup>
import { sysFilterMethod } from '@/utils/selectFilter'
import { getSimpleDeptList } from '@/api/system/dept'
import { handleTree } from '@/utils/tree'
import { renderFinger } from '@/utils/commonRender'

import { dataStandardsPage } from '@/api/dataStandards/standards/index'
import { getSimpleSystemList } from '@/api/asset/taskManage'
import { getInfoFileManage, intoFileManage } from '@/api/develop/featureLibrary/fingerprint'
import {
  valueConfGetByValue,
  valueConfFieldValue,
  valueConfGetByValueTree
} from '@/api/dataStandards/assuranceValue/index'
import * as assuranceApi from '@/api/dataStandards/assurance/index'
import { infoPage } from '@/api/dataStandards/info/index'
import { levelPage } from '@/api/strategyManage/level/index'

import FileChose from './FileChose.vue'

// 机构选项框配置
const cascaderProps = {
  checkStrictly: true,
  label: 'name',
  value: 'id',
  children: 'children',
  emitPath: false
}
// 系统选项框配置
const systemCascaderProps = {
  checkStrictly: true,
  label: 'value',
  value: 'id',
  children: 'children',
  emitPath: false
}
// 分类选项框配置
const classProps = {
  value: 'field1',
  label: 'field1_name',
  checkStrictly: true,
  expandTrigger: 'hover',
  emitPath: false
}

// 数据标准下拉选项
const templateList = ref([])
const getTemplateList = async () => {
  const { data } = await dataStandardsPage({
    page: 1,
    pageSize: 999,
    status: '1',
    type: 0
  })
  templateList.value = data
}

const formRef = ref()

const dialogVis = ref(false)
// 打开弹窗
const open = async (data) => {
  dialogVis.value = true
  // formRef?.value?.resetField()
  tableData.value = await getInfoFileManage(data.map((item) => item.id))
  tableData.value.forEach(async (item, index) => {
    if (item.standard) {
      item.standard = null
      item.classification = null
      item.level = null
      item.deptId = null
      item.systemId = null
    }
  })
  console.log('tableData', tableData.value)
}
const fileChoseRef = ref()
// 打开选择文件弹窗
const handleImport = () => {
  fileChoseRef.value?.open()
}

// 删除引入
const handleDelete = async () => {
  const data = tableRef.value.getSelectionRows().map((item) => item.id)
  if (data.length == 0) {
    ElMessage.warning('请选择要删除的引用文件')
    return
  }
  tableData.value = tableData.value.filter((item) => !data.includes(item.id))
}
defineExpose({ open }) // 暴露给父组件的方法

const formData = reactive({
  tableData: []
})
// 表格数据
const tableData = toRef(formData, 'tableData')

// 所属机构
const deptList = ref([])
async function getDeptList() {
  const data = await getSimpleDeptList()
  deptList.value = data
}

// 所属系统
const systemList = ref([])
async function getSystemList() {
  const data = await getSimpleSystemList()
  systemList.value = handleTree(data, 'id', 'pid')
}

onMounted(async () => {
  await Promise.all([getTemplateList(), getDeptList(), getSystemList()])
})

// 分类改变
function classificationChange(value, index) {
  console.log('classificationChange', value, index, tableData.value[index])
  // 分级置空
  tableData.value[index].level = ''
  tableData.value[index].classChange(value, 1, index)
}

async function templateChange(index) {
  console.log('templateChange', index, tableData.value[index])
  await getClassLevelList(tableData.value[index].standard, index)
  getColumn(tableData.value[index].standard, index)
  getInfoList(tableData.value[index].standard, index)
  await getDownList(index)

  tableData.value[index]['level'] = ''
  tableData.value[index]['classification'] = ''

  tableData.value[index].classChange(tableData.value[index].classification, 1, index)

  if (
    tableData.value[index].downLists?.length > 0 &&
    tableData.value[index].tempClassList?.length > 0
  ) {
    tableData.value[index].classOptions = setClassOptionsMap(
      tableData.value[index].flattenDownList,
      tableData.value[index].tempClassList
    )
  }
}

const setClassOptionsMap = (data, tempClassList) => {
  return data.map((item) => {
    item.field1_name = tempClassList.find((fitem) => fitem.key == item.field1)?.value
    item.disabled = item.isSelect == '0'
    item.children.length && setClassOptionsMap(item.children, tempClassList)
    return item
  })
}

// 获取内容配置中分类分级的下拉
// const tempClassList = ref([])
// const tempLevelList = ref([])
const getClassLevelList = async (id, index) => {
  tableData.value[index].tempClassList = await valueConfFieldValue({
    dataStandardId: id,
    type: '1'
  })
  const levelOptions = await valueConfFieldValue({
    dataStandardId: id,
    type: '2'
  })
  let levelOptionsData = levelOptions.map((ite) => {
    return {
      ...ite,
      disabled: false
    }
  })

  tableData.value[index].tempLevelList = levelOptionsData
}

// const columnList = ref([])
// 获取表格列（制度信息）
const getColumn = async (id, index) => {
  const data = await assuranceApi.assurancePage({
    dataStandardId: id,
    display: 1,
    page: 1,
    pageSize: 20
  })
  if (data.length > 0) {
    tableData.value[index].columnList = data
  } else {
    tableData.value[index].columnList = []
  }
}

// const extendList = ref([])
// 获取模板扩展字段列表
const getInfoList = async (id, index) => {
  const data = await infoPage({
    page: 1,
    pageSize: 20,
    dataStandardId: id, //固定一个模板先用于测试
    display: '1'
  })
  tableData.value[index].extendList = data.map((item) => {
    return {
      ...item,
      presetContentMap: item.presetContent ? JSON.parse(item.presetContent) : []
    }
  })
  await getLevelList(index)
}

// 获取等级下拉列表
// const levelList = ref([])
// const allLevelList = ref([])
const getLevelList = async (index) => {
  const { data } = await levelPage({ page: 1, pageSize: 999 })
  const deadLineConf = tableData.value[index].extendList.find((item) => item.index === 3)
  if (deadLineConf && deadLineConf.presetContent && deadLineConf.presetContent !== '[]') {
    const presetCodes = JSON.parse(deadLineConf.presetContent)
    const arr = data.filter((item) => presetCodes.includes(item.levelCode))
    tableData.value[index].levelList = arr.map((ite) => {
      ite.levelCode = ite.levelCode + ''
      return ite
    })
  } else {
    tableData.value[index].levelList = data.map((ite) => {
      ite.levelCode = ite.levelCode + ''
      return ite
    })
  }
  tableData.value[index].allLevelList = data
}

// 分类修改
let classChange = (e, scopeIndex, index) => {}

const cascaderAllOptions = ref([])

import useCascader from '@/hooks/event/useCascader'
import { classificationCreate } from '@/api/dataStandards/classification'

/** 查询非分类分级的下拉列表 */
// const downLists = ref([])
// const dropdownData = ref()
// const flattenDownList = ref([])

const getDownList = async (index) => {
  const data = await valueConfGetByValue({
    dataStandardId: tableData.value[index].standard
  })
  let treeData = await valueConfGetByValueTree({
    dataStandardId: tableData.value[index].standard
  })
  console.log(
    'treeData',
    treeData,
    data,
    tableData.value[index],
    tableData.value[index].tempLevelList
  )
  let { inFiledChange, typeChange, byValuetreeData, byValueData, cascaderSelectOptions } =
    useCascader({
      treeData,
      data,
      listValue: ref(tableData.value),
      tempLevelList: tableData.value[index].tempLevelList
    })

  tableData.value[index].classChange = typeChange
  console.log('cascaderSelectOptions', cascaderSelectOptions.value)
  cascaderAllOptions.value = cascaderSelectOptions.value

  if (data.length > 0) {
    tableData.value[index].downLists = byValueData
    tableData.value[index].flattenDownList = byValuetreeData
    tableData.value[index].dropdownData = convertToDropdownData(tableData.value[index].downLists)
  } else {
    tableData.value[index].downLists = data
  }
}
const convertToDropdownData = (data) => {
  const dropdownData = {}
  Object.keys(data[0]).forEach((key) => {
    if (key.startsWith('field')) {
      if (key.startsWith('field3'))
        dropdownData[key] = Array.from(
          new Set(data.map((item) => item[key]).filter((value) => value !== ''))
        )
    }
  })
  return dropdownData
}

const emit = defineEmits(['success'])
const tableRef = ref()
const confirmImport = async () => {
  if (tableData.value.length == 0) {
    ElMessage.warning('请选择要引入的文件')
    return
  }
  const valid = await formRef.value.validate()
  if (!valid) return
  await intoFileManage(
    tableData.value.map((item) => {
      const {
        id,
        name,
        md5,
        kfs,
        pfs,
        psa,
        fileId,
        fileFrom,
        deptId,
        systemId,
        standard,
        level,
        classification,
        ...elseData
      } = { ...item }
      return {
        id,
        name,
        md5,
        kfs,
        pfs,
        psa,
        fileId,
        fileFrom,
        deptId,
        systemId,
        standard,
        level,
        classification
      }
    })
  )
  emit('success')
  dialogVis.value = false
}
</script>

<style scoped lang="scss">
:deep(.el-form-item--default) {
  margin-bottom: 0 !important;
}
.footer-wrap {
  display: flex;
  justify-content: end;
}
</style>
